<?php


namespace App\Http\Controllers;


use App\Exceptions\BlackException;
use App\Helpers\Api\ApiResponse;
use App\Helpers\Api\DestroyTrait;
use App\Helpers\Api\EditStatusTrait;
use App\Helpers\Api\InfoTrait;
use App\Helpers\Api\MiniProgramTrait;
use App\Helpers\Api\PayTrait;
use App\Helpers\Api\StoreTrait;
use App\Helpers\Api\TtMiniTrait;
use App\Helpers\Api\UnionPayTrait;
use App\Models\User;
use Dingo\Api\Routing\Helpers;

class BaseController extends Controller
{

    use Helpers, ApiResponse, MiniProgramTrait, UnionPayTrait, DestroyTrait, InfoTrait, StoreTrait, EditStatusTrait, PayTrait, TtMiniTrait;
    static $is_init = false;

    public function __construct()
    {
        if (!self::$is_init) {
            $request = app('Illuminate\Http\Request');
            \Log::info(url()->current() . ' header ' . $request->header('version'));
            \Log::info(var_export($request->input(), true));
            $user = $this->getUser();

            if ($user && $user->is_black == 1) {
                throw new BlackException('你已违规被加入黑名单');
            }
            self::$is_init = true;
        }
    }

    /**
     * Get the token array structure.
     * @param $token
     * @param $user
     * @return mixed
     */
    protected function respondWithToken($token, $user = null)
    {
        return $this->success([
            'info' => $user ?: $this->getUser(),
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }

    /**
     * @return User
     */
    protected function getUser()
    {
        return auth()->user();
    }

    protected function getUserId() {
        return $this->getUser()->id ?? 0;
    }

    function paginate($pagination, $extra = null, $total = false, $has_more_page = false) {
        $arr = [
            'list' => $pagination->items(),
            'total' => $total ?: $pagination->total(),
            'has_more_page' => $has_more_page ?: $pagination->hasMorePages(),
            'extra' => $extra
        ];
        return $this->success($arr);
    }

    protected function cache($input, $tags, $func) {
        ksort($input);
        $cache_key = substr(md5(http_build_query($input)), 8, -8);
        return \Cache::tags($tags)->rememberForever($cache_key, $func);
    }

}

